<script setup lang="ts">
import type { FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { roleList } from '../../api/roles'
import md5 from 'js-md5'
import { encode } from 'js-base64'

interface Props {
  data?: Record<string, any> | never | null
  status?: string | never | null
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = ref<Record<string, any>>({})

const rules = reactive<FormRules>({
  userName: [{ required: true, message: '昵称不能为空!', trigger: 'blur' }],
  phone: [{ required: true, message: '手机号不能为空!', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空!', trigger: 'blur' }],
  roleIdList: [{ required: true, message: '角色不能为空!', trigger: 'blur' }]
})

const rolesOpts = ref<any[]>([])

const getOptions = async () => {
  let res: any = await roleList()
  rolesOpts.value = res.map((item: any) => {
    return {
      label: item.roleName,
      value: item.roleId
    }
  })
}
getOptions()

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      if (['userId', 'userName', 'phone', 'password', 'roleIdList'].indexOf(key) > -1) {
        form.value[key] = props.data![key]
      }
    })
  }
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form.value).forEach((key: string) => {
    if (key === 'password') {
      result[key] = encode(md5(form.value[key]))
    } else {
      result[key] = form.value[key]
    }
  })
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="昵称:" prop="userName">
        <el-input v-model="form.userName" type="text" placeholder="请输入内容" maxlength="20" show-word-limit> </el-input>
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model="form.phone" type="text" placeholder="请输入内容" maxlength="20" show-word-limit> </el-input>
      </el-form-item>
      <el-form-item v-if="props.status == 'add'" label="密码:" prop="password">
        <el-input v-model="form.password" type="text" placeholder="请输入内容" maxlength="20" show-word-limit show-password> </el-input>
      </el-form-item>
      <el-form-item label="角色:" prop="roleIdList">
        <el-select v-model="form.roleIdList" multiple placeholder="角色" style="width: 100%">
          <el-option v-for="item in rolesOpts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.form-wrapper {
  width: 320px;
}
</style>
